import { register, updateUserInfo } from '@/api/user';
import { useToast } from 'wot-design-uni';
import type { TRegisterReq } from '@/api/user/type';
import type { UploadFile } from 'wot-design-uni/components/wd-upload/types';
import { ResultCodeEnum } from '@/enums';
import { useUserStore } from '@/store';

export const useRegister = (isAgree: Ref<boolean>) => {
  const userStore = useUserStore();
  const isEdit = ref(false);

  onLoad((options) => {
    console.log('打印***options', options);
    isEdit.value = options?.type === 'edit';
    if (isEdit.value) {
      uni.setNavigationBarTitle({
        title: '编辑资料'
      });
      model.name = userStore.userInfo.name;
      model.email = userStore.userInfo.email;
      model.phone = userStore.userInfo.phone;
      model.avatar = userStore.userInfo.avatar;
      fileList.value = [{ url: userStore.userInfo.avatar }];
    }
  });

  const fileList = ref<UploadFile[]>([]);
  const model = reactive<TRegisterReq>({
    name: '',
    password: '',
    email: '',
    phone: '',
    avatar: ''
  });

  const action = import.meta.env.VITE_APP_UPLOAD_URL;

  const handleChange = ({ fileList }: any) => {
    if (fileList.length) {
      model.avatar = JSON.parse(fileList[0].response).data.url;
    }
  };

  const form = ref();
  const { success: showSuccess, info } = useToast();

  const handleSubmit = async () => {
    const { valid } = await form.value.validate();
    console.log('打印***valid', valid);
    if (!valid) return;
    if (!isAgree.value) return info({ msg: '请阅读并同意隐私保护指引' });
    if (isEdit.value) {
      await updateInfo();
    } else {
      await registerInfo();
    }
  };

  const registerInfo = async () => {
    const res = await register(model);
    if (res.code === ResultCodeEnum.SUCCESS) {
      showSuccess({
        msg: '注册成功'
      });
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/center/login/index'
        });
      }, 1000);
    }
  };

  const updateInfo = async () => {
    const res = await updateUserInfo({
      name: model.name,
      email: model.email,
      phone: model.phone,
      avatar: model.avatar,
      id: userStore.userInfo.id
    });
    if (res.code === ResultCodeEnum.SUCCESS) {
      showSuccess({
        msg: '更新成功'
      });
      userStore.setUserInfo({
        ...res.data,
        accessToken: userStore.userInfo.accessToken,
        refreshToken: userStore.userInfo.refreshToken
      });
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/center/index'
        });
      }, 1000);
    }
  };

  return {
    isEdit,
    form,
    model,
    fileList,
    action,
    handleChange,
    handleSubmit
  };
};
